<?php
namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use Da\QrCode\QrCode;//引入类
use common\models\WorksComment;
use common\models\WorksCollection;
use common\models\Tools;
use common\models\UserFriendRequest;
use common\models\Chat;
use common\models\UserFriend;
/**
 * Site controller
 */
class SiteController extends Controller
{
    public $enableCsrfValidation=false;
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
//                'actions' => [
//                    'logout' => ['post'],
//                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        //$name = \common\models\Tools::GetSafeParam("name", "", 1);
        $categories = \common\models\Category::getTopCategories();//所有一级作品分类
        //热门作品top10展示
        $topTenWorks = \common\models\Works::getPageWorks(0,10);
        
        foreach ($topTenWorks as $key=>$works){
            //获取作者头像
            $topTenWorks[$key]['userheadimg'] = \common\models\User::getUserHeadImg($works['authorid']);
            //获取评论条数
            $topTenWorks[$key]['comment_num'] = WorksComment::getWorksCommentNum($works['id']);
            //获取被喜欢的次数
            $topTenWorks[$key]['collect_num'] = WorksComment::getWorksCollectNum($works['id']);
            $topTenWorks[$key]['is_collection'] = Yii::$app->user->isGuest ? 0: WorksCollection::checkExist(Yii::$app->user->identity->id,$works['id']);
            $topTenWorks[$key]['addtime'] = Tools::calculateTimelong($works['addtime']);
        }
        
        //获取未读消息数量
        $unread_works_msgnum = Yii::$app->user->isGuest ? 0:WorksComment::getUnreadMsgNum(Yii::$app->user->identity->id);
        
        //获取作品最新的未读消息
        $latestMsg = Yii::$app->user->isGuest ? "":WorksComment::getLatestMsg(Yii::$app->user->identity->id);
        
        //好友请求消息
        $friends_request_msg_num = Yii::$app->user->isGuest ? 0: UserFriendRequest::getUserRequestMsgNum(Yii::$app->user->identity->id);
        $friends_request_msg = Yii::$app->user->isGuest ? "": UserFriendRequest::getUserRequestMsg(Yii::$app->user->identity->id);
        
        //好友聊天消息
        $friends_msg = Yii::$app->user->isGuest ? []: Chat::getUserFriendsMsg(Yii::$app->user->identity->id);
        
        if(empty($friends_msg)){
            $friends_msg_total_unreadnum = 0;
            $friends_chat = [];
        }else{
            $friends_msg_total_unreadnum = $friends_msg['total_unreadnum'];
            $friends_chat = $friends_msg['chats'];
        }
        
        $have_chat = empty($friends_chat) ? 0 : 1;
        
        //获取好友列表信息
        
        $friends_list = Yii::$app->user->isGuest ? []: UserFriend::getFriendsList(Yii::$app->user->identity->id);
//        echo "<pre>";print_r($friends_list);exit;
        //未读消息数量累计
        $unreadMsgNum = $unread_works_msgnum + $friends_request_msg_num + $friends_msg_total_unreadnum;
//        echo $unreadMsgNum;exit;
        return $this->render('index',['categories'=>$categories,'topTenWorks'=>$topTenWorks,'unreadMsgNum'=>$unreadMsgNum,'latestMsg'=>$latestMsg,'friends_request_msg'=>$friends_request_msg,'friends_chat'=>$friends_chat,'have_chat'=>$have_chat,'friends_list'=>$friends_list]);
    }
    
    
    public function actionWorkspage(){
        $page = Tools::GetSafeParam("page", 0, 0);
        $category = Tools::GetSafeParam("category", 0, 0);
        $pageNum = 10;
        $begin = ($page-1)*$pageNum;
        $userid =  Yii::$app->user->isGuest ? 0 : Yii::$app->user->identity->id;
        $data = \common\models\Works::getPageWorks($begin,$pageNum,$category,$userid);
        
        if(!empty($data)){
            foreach ($data as $key=>$works){
                //获取作者头像
                $data[$key]['userheadimg'] = \common\models\User::getUserHeadImg($works['authorid']);
                //获取评论条数
                $data[$key]['comment_num'] = WorksComment::getWorksCommentNum($works['id']);
                //获取被喜欢的次数
                $data[$key]['collect_num'] = WorksComment::getWorksCollectNum($works['id']);
                $data[$key]['is_collection'] = Yii::$app->user->isGuest ? 0: WorksCollection::checkExist(Yii::$app->user->identity->id,$works['id']);
                $data[$key]['addtime'] = Tools::calculateTimelong($works['addtime']);
            }
        }
        
        $output = [];
        $output['success'] = 1;
        $output['data'] = $data;
        Tools::outputjson($output);
    }
    


//    public function actionGetqrcode() 
//    {
//        $qrCode = (new QrCode('http://www.baidu.com'))
//            ->setSize(100)
//            ->setMargin(5)
//            ->useForegroundColor(51, 153, 255);
//
//        // now we can display the qrcode in many ways
//        // saving the result to a file:
//
//        //$qrCode->writeFile(__DIR__ . '/code.png'); // writer defaults to PNG when none is specified
//
//        // display directly to the browser 
//        header('Content-Type: '.$qrCode->getContentType());
//        echo $qrCode->writeString();
//    }
	

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout = "loglayout";
        
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $query_str = $_SERVER['QUERY_STRING'];
        
        if(strpos($query_str,"returnurl") === false){
            $return_url = '/';
        }else{
            $return_url = substr($query_str, 10);
        }
        
        return $this->render('login',['return_url'=>$return_url]);
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $this->layout = "loglayout";
        $post = Yii::$app->request->post();
        if(!empty($post)){
            $code = $post['code'];
            $hashcode = $post['hashcode'];
            $string = Tools::decrypt($hashcode, Yii::$app->params['sms_encrypt_key']);
            $decrypt_arr = explode('_', $string);
            if($decrypt_arr[1] != $code){
                echo "验证码错误！";exit;
            }
            $user = new \common\models\User();
            $user->username = $post['username'];
            $user->mobile = $post['mobile'];
            $user->setPassword($post['passwd']);
            $user->generateAuthKey();

            if($user->save()){
                $login = Yii::$app->user->login($user, 3600 * 24 * 30);
                \common\models\WebsocketSever::distributeServer($user->id);
                $user->usercode = Tools::getUserCode(time(), $user->id);
                $user->save();
                return $this->redirect('/');
            }
        }
        

        return $this->render('signup');
    }
    
//    public function actionSignup()
//    {
//        $model = new SignupForm();
//        if ($model->load(Yii::$app->request->post())) {
//            if ($user = $model->signup()) {
//                if (Yii::$app->getUser()->login($user)) {
//                    return $this->goHome();
//                }
//            }
//        }
//
//        return $this->render('signup', [
//            'model' => $model,
//        ]);
//    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }
}
